package com.example.zhongshuishi.controller;

import cn.hutool.core.bean.BeanUtil;
import com.example.zhongshuishi.DemoConfig;
import com.example.zhongshuishi.entity.CustomerUserDetails;
import com.example.zhongshuishi.entity.PaymentNotifyDTO;
import com.example.zhongshuishi.entity.PaymentQueryDTO;
import com.example.zhongshuishi.entity.StudentDto;
import com.example.zhongshuishi.mapper.StudentMapper;
import com.example.zhongshuishi.service.StudentService;
import com.example.zhongshuishi.service.PaymentService;
import com.example.zhongshuishi.utils.KSXJWTUtil;
import com.example.zhongshuishi.utils.KSXPostUtil;
import com.example.zhongshuishi.utils.OurpayKit;

import com.example.zhongshuishi.utils.SHA256Utils;
import com.github.pagehelper.PageInfo;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.Timestamp;
import java.util.*;

import org.springframework.validation.BindingResult;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

/**
 * @author 鑫程垬纾
 * @version 1.0
 * @description TODO
 * @date 2025/3/29 12:27
 */
@RestController
@RequestMapping("/api/student")
public class StudentController {
    Logger logger = LoggerFactory.getLogger(StudentController.class);
    @Autowired
    private PaymentService paymentService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private StudentMapper studentMapper;

    @PostMapping("/add")
    public ResponseEntity<?> addStudent(@Validated @RequestBody StudentDto student, BindingResult bindingResult) throws Exception {
//        if (bindingResult.hasErrors()) {
//            return ResponseEntity.badRequest().body(bindingResult.getAllErrors());
//        }
        String teacherName = student.getTeacher();
        if (teacherName != null && !teacherName.isEmpty()) {
            String teacherId = studentMapper.isTeacherExist(teacherName);
            if (teacherId == null || teacherId.isEmpty()) {
                return ResponseEntity.badRequest()
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(Collections.singletonMap("message", "该教师不存在"));
            }
            student.setTeacherId(teacherId); // 设置教师ID
        }
//        String stuPhone = student.getStuPhone();
//        if (stuPhone != null && !stuPhone.isEmpty()) {
//            StudentDto existingStudent = studentService.getStudentByPhone(stuPhone);
//            if (existingStudent != null) {
//                return ResponseEntity.badRequest()
//                        .contentType(MediaType.APPLICATION_JSON)
//                        .body(Collections.singletonMap("message", "该手机号已存在"));
//            }
//        }
      //  student.setId((UUID.randomUUID().toString().replace("-", "")));
        student.setJiaocai("98");
        student.setApplication("2200");
        student.setPayment("2298"); // 固定支付金额为2298元
        Date date = new Date();
        student.setCreatTime(date);
     //   studentService.addStudent(student);
        //student.setId(100);
        String id = student.getId();
        if (id == null) {
            studentService.addStudent(student);
            student.setId(student.getId());
            studentService.addTraining(student);

        } else {
            studentService.updateById(student);
            studentService.updateTraining(student);

        }

//        student.setOrderNo("ZSS" + UUID.randomUUID().toString().replace("-", ""));
//        String orderNo = student.getOrderNo();
//        student.getPayChannel();
//
//        ResponseEntity<?> payResponse = pay(student);
//
//        studentService.addStudent(student);
//        if (payResponse.getStatusCode() != HttpStatus.OK) {
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("报名成功缴费失败: " + payResponse.getBody());
//        }
//
//        Map<String, Object> response = new HashMap<>();
//        response.put("orderNo", orderNo);
//        response.put("qrCode", payResponse.getBody());
//        return ResponseEntity.ok(response);
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_JSON)
                .body(Collections.singletonMap("message", "报名成功!"));
    }


    @DeleteMapping("/deleteStudentById")
    public int deleteStudent(@RequestParam String id) {
        return studentService.deleteStudent(id);
    }

    @PutMapping("/update")
    public int updateStudent(@RequestBody StudentDto student) {
        return studentService.updateStudent(student);
    }

    @PutMapping("/updateById")
    public int updateById(@RequestBody StudentDto student) {
        return studentService.updateById(student);
    }


    @GetMapping("/getStudentById")
    public StudentDto getStudentById(String id) {
        return studentService.getStudentById(id);

    }

    @GetMapping("/getStudentByPhone")
    public StudentDto getStudentByPhone(String phone) {
        return studentService.getStudentByPhone(phone);

    }

    @GetMapping("/list")
    public List<StudentDto> getAllStudents() {
        return studentService.getAllStudents();
    }


    //根据老师查询学生
    @GetMapping("/personal/list")
    public PageInfo getPersonalStudents(Integer teacherId,String teacher, Integer wxId, String stuName, String stuIdnumber, String stuPhone, @NotNull Integer currPage, @NotNull Integer pageSize) {
        try{
            logger.info("/personal/list getPersonalStudents start");
            List<StudentDto> studentDtos = studentService.selectByPersonnal(teacherId,teacher, wxId, stuName, stuIdnumber, stuPhone, currPage, pageSize);
            PageInfo pageInfo = new PageInfo( studentDtos );
            return pageInfo;
        }catch (Exception e ){
            e.printStackTrace();
            logger.error("/personal/list getPersonalStudents error ="+e.getMessage());
        }
        return null;
    }
//    @PostMapping("/demo")
//    public String loginKaoShiXing( @RequestBody StudentDto student) {
//        String postUrl = KSXJWTUtil.getPostUrl("201");
//
//        Map<String, Object> params = new HashMap<>();
//        params.put("user_id", "2");
//        params.put("user_name", "李四");
//        params.put("department", "总部/技术部");
//
//        String rawPassword = "123456";
//        String encryptedPassword = SHA256Utils.getSHA256(rawPassword);
//        params.put("password", encryptedPassword);
//
//        String response = KSXPostUtil.sendPost(postUrl, params);
//        System.out.println("响应结果: " + response);
//
//        String redirectUrl = null;
//        if (response != null) {
//            JsonObject jsonResponse = JsonParser.parseString(response).getAsJsonObject();
//            if (jsonResponse.get("code").getAsInt() == 10000) {
//                redirectUrl = jsonResponse.get("url").getAsString();
//                System.out.println("重定向URL: " + redirectUrl);
//            }
//        }
//        return redirectUrl;
//    }


}


